package com.pospi.xstore.ui.cash_ui;

import android.Manifest;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.github.dfqin.grantor.PermissionListener;
import com.github.dfqin.grantor.PermissionsUtil;
import com.google.gson.Gson;
import com.lany.sp.SPHelper;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.maning.library.MClearEditText;
import com.mylhyl.circledialog.CircleDialog;
import com.mylhyl.circledialog.params.ProgressParams;
import com.mylhyl.circledialog.view.listener.OnCreateBodyViewListener;
import com.pospi.xstore.App;
import com.pospi.xstore.R;
import com.pospi.xstore.adapter.ScanReceiptAdapter;
import com.pospi.xstore.dao.GoodsDao;
import com.pospi.xstore.dao.OrderDao;
import com.pospi.xstore.dto.CashierMsgDto;
import com.pospi.xstore.dto.GoodsDto;
import com.pospi.xstore.dto.OrderDto;
import com.pospi.xstore.dto.Tablebeen;
import com.pospi.xstore.http.LoadServer;
import com.pospi.xstore.http.MaxNO;
import com.pospi.xstore.ui.CaptureActivity;
import com.pospi.xstore.ui.base.BaseActivity;
import com.pospi.xstore.ui.pay_ui.PayActivity;
import com.pospi.xstore.ui.pay_ui.UnionConfig;
import com.pospi.xstore.ui.vip_ui.VipActivity;
import com.pospi.xstore.ui.vip_ui.VipBeen;
import com.pospi.xstore.util.Api;
import com.pospi.xstore.util.Constant;
import com.pospi.xstore.util.DoubleSave;
import com.pospi.xstore.util.GetData;
import com.pospi.xstore.util.PareseJson;
import com.pospi.xstore.util.PromotionUtil;
import com.pospi.xstore.util.SaveOrderInfo;
import com.pospi.xstore.util.TurnSize;
import com.pospi.xstore.view.swipemenulistview.SwipeMenu;
import com.pospi.xstore.view.swipemenulistview.SwipeMenuCreator;
import com.pospi.xstore.view.swipemenulistview.SwipeMenuItem;
import com.pospi.xstore.view.swipemenulistview.SwipeMenuListView;
import com.zaaach.toprightmenu.MenuItem;
import com.zaaach.toprightmenu.TopRightMenu;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class ScanReceiptActivity extends BaseActivity {

    @Bind(R.id.tv_cashier)
    TextView tvCashier;
    @Bind(R.id.sale_et)
    EditText saleEt;
    @Bind(R.id.iv_vip)
    ImageView ivVip;
    @Bind(R.id.iv_scan)
    ImageView ivScan;
    @Bind(R.id.tv_order_id)
    TextView tvOrderId;
    @Bind(R.id.lv_goods)
    SwipeMenuListView lvGoods;
    @Bind(R.id.tv_money)
    TextView tvMoney;
    @Bind(R.id.retain)
    TextView retain;
    @Bind(R.id.settle)
    TextView settle;
    @Bind(R.id.tv_qd)
    TextView tv_qd;
    @Bind(R.id.ll_bottom)
    LinearLayout llBottom;
    @Bind(R.id.vip_serach)
    ImageView vip_serach;
    @Bind(R.id.activity_main)
    LinearLayout activity_main;

    private GoodsDao goodsDao;
    private List<GoodsDto> goodsDtos = new ArrayList<>();
    private ScanReceiptAdapter adapter;
    public final static String PUT_MONEY = "money";
    public final static String PUT_MAXNO = "maxNO";

    private EditText et_num;
    private EditText et_zr;
    private EditText et_zc;

    private String maxNO;
    private OrderDto orderDto;
    private DialogClickListener clicklistener = new DialogClickListener();
    private DialogRadioButton buttonListener = new DialogRadioButton();
    private AlertDialog diacountDialog;

    private RadioButton radioButton_zr;
    private RadioButton radioButton_zc;

    private GoodsDto selectGood;
    private PromotionUtil util;
    private EditText et_zr1;
    private String vipinfo = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentLayout(R.layout.activity_scan_receipt);
        ButterKnife.bind(this);
        setTitle("扫码收款");
        setMenuText("清空");
        util = new PromotionUtil(this);

        lvGoods.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                selectGood = goodsDtos.get(position);
                showSingleDialog();
            }
        });
        lvGoods.setFocusable(false);
        saleEt.requestFocus();



        LinearLayout activity_main = (LinearLayout) findViewById(R.id.activity_main);

        activity_main.setOnTouchListener(new View.OnTouchListener()

        {
            public boolean onTouch(View arg0, MotionEvent arg1) {
                InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);

                return imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);

            }

        });

        lvGoods.setOnTouchListener(new View.OnTouchListener()

        {
            public boolean onTouch(View arg0, MotionEvent arg1) {
                InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);

                return imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);

            }

        });

        initWeidgets();
    }


    private MClearEditText et_sl;
    EditText single_zr;
    EditText single_zk;
    public void showSingleDialog() {

        new CircleDialog.Builder(this)
                .setBodyView(R.layout.dialog_single_discount, new OnCreateBodyViewListener() {
                    @Override
                    public void onCreateBodyView(View view) {
                        et_sl = view.findViewById(R.id.et_goods_num);
                        single_zr = view.findViewById(R.id.et_zr);
                        single_zk = view.findViewById(R.id.et_zk);
                        TextView tv_dj = view.findViewById(R.id.tv_dj);
                        tv_dj.setText("单价："+selectGood.getPrice());
                        et_sl.setText(selectGood.getNum() + "");
                    }
                })
                .setPositive("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        hintKbOne();
                        String num = et_sl.getText().toString().trim();
                        String zr = single_zr.getText().toString().trim();
                        String zk = single_zk.getText().toString().trim();
                        if (!num.isEmpty()) {
                            selectGood.setNum(Double.parseDouble(num));
                        }
                        if (!zk.isEmpty() && !zr.isEmpty()) {
                            Toast.makeText(ScanReceiptActivity.this, "请选择一种优惠", Toast.LENGTH_SHORT).show();
                        } else if (zk.isEmpty() && zr.isEmpty()) {

                        } else {
                            try {
                                if (zr.isEmpty()) {
                                    zr = "0";
                                }
                                if (zk.isEmpty()) {
                                    zk = "1";
                                } else {
                                    zr = String.valueOf((Double.parseDouble(zk) / 100) * selectGood.getNum() * selectGood.getPrice());
                                }
                                if (Double.parseDouble(zr) > selectGood.getNum() * selectGood.getPrice()) {
                                    Toast.makeText(ScanReceiptActivity.this, "折扣金额不能大于商品总价", Toast.LENGTH_SHORT).show();
                                } else {
                                    selectGood.setLszk(Double.parseDouble(zr));
                                }
                            } catch (Exception e) {
                                Toast.makeText(ScanReceiptActivity.this, "请输入正确的折让", Toast.LENGTH_SHORT).show();
                            }

                        }

                        adapter.notifyDataSetChanged();
                        setData();

                    }
                })
                .setCancelable(false)
                .setTitle(selectGood.getName())
                .setNegative("取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
//                        hintKbOne();
                    }
                })
                .show();

//        View discountView = LayoutInflater.from(this).inflate(R.layout.goods_edit, null);
//        diacountDialog = new AlertDialog.Builder(this)
//                .setView(discountView)
//                .create();
//        Button cancle = (Button) discountView.findViewById(R.id.btn_detail_cancle);
//        Button sure = (Button) discountView.findViewById(R.id.btn_detail_sure);
//
//        et_num = (EditText) discountView.findViewById(R.id.et_num);
//        TextView name = (TextView) discountView.findViewById(R.id.tv_name);
//        et_zr = (EditText) discountView.findViewById(R.id.et_zr);
//        et_zc = (EditText) discountView.findViewById(R.id.et_zc);
//
//        ImageView jia = (ImageView) discountView.findViewById(R.id.iv_jia);
//        ImageView jian = (ImageView) discountView.findViewById(R.id.iv_jian);
//
//        radioButton_zr = (RadioButton) discountView.findViewById(R.id.radioButton_zr);
//        radioButton_zc = (RadioButton) discountView.findViewById(R.id.radioButton_zc);
//        radioButton_zr.setChecked(true);
//        radioButton_zc.setChecked(false);
//
//        cancle.setOnClickListener(clicklistener);
//        sure.setOnClickListener(clicklistener);
//        jia.setOnClickListener(clicklistener);
//        jian.setOnClickListener(clicklistener);
//
//
//        radioButton_zc.setOnCheckedChangeListener(buttonListener);
//        radioButton_zr.setOnCheckedChangeListener(buttonListener);
//        diacountDialog.show();
//        et_num.setText(String.valueOf(selectGood.getNum()));
//        name.setText(selectGood.getName());

    }

    @Override
    protected void onStart() {
        super.onStart();
        saleEt.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                judgeCode(saleEt.getText().toString().trim());
                return false;
            }
        });
    }

    @Override
    public void onMenuClick(View view) {
        super.onMenuClick(view);
        //"清空"按钮的点击事件
//        showitem();
        deleteOrder();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);

//        tvOrderId.setText(String.valueOf(maxNO));
        String goodsInfo = intent.getStringExtra("goods");
        if (goodsInfo != null) {
            List<GoodsDto> list = new ArrayList<>();
            list = SaveOrderInfo.changeToList(goodsInfo);
            goodsDtos.addAll(list);
            adapter.notifyDataSetChanged();
            setData();
        }
        Log.i("goods", goodsInfo + "------");
        String ok = intent.getStringExtra("pay");
        if (ok != null) {
            maxNO = MaxNO.getMaxNo(getApplicationContext());
            goodsDtos.clear();
            adapter.notifyDataSetChanged();
            setData();
            vipBeen = null;
            tvOrderId.setText("会员号：");
        }


        orderDto = (OrderDto) intent.getSerializableExtra("rest");
        if (orderDto != null) {
            maxNO = orderDto.getMaxNo();
            Log.i("跳转之后", "NO" + orderDto.getMaxNo() + "");
            List<GoodsDto> list = SaveOrderInfo.changeToList(orderDto.getOrder_info());
            if (!orderDto.getmTableId().equals("")) {
                vipBeen = new Gson().fromJson(orderDto.getmTableId(), VipBeen.class);
                tvOrderId.setText("会员号："+vipBeen.getNum());
            }
            goodsDtos.clear();
            goodsDtos.addAll(list);
            adapter.notifyDataSetChanged();
            setData();
        }

    }


    public void initWeidgets() {
        orderDto = (OrderDto) getIntent().getSerializableExtra(RestOrderActivity.REST_ORDER);
        if (orderDto != null) {
            maxNO = orderDto.getMaxNo();
            Log.i("跳转之后", "NO" + orderDto.getMaxNo() + "");
            goodsDtos = SaveOrderInfo.changeToList(orderDto.getOrder_info());
        } else {

            maxNO = MaxNO.getMaxNo(getApplicationContext());

        }
        goodsDao = new GoodsDao(getApplicationContext());

//        tvOrderId.setText(String.valueOf(maxNO));
        adapter = new ScanReceiptAdapter(getApplicationContext(), goodsDtos);

        int which = getSharedPreferences("islogin", MODE_PRIVATE).getInt("which", 0);
//        List<CashierMsgDto> cashierMsgDtos = new PareseJson().parese(getSharedPreferences("cashierMsgDtos", MODE_PRIVATE).getString("cashierMsgDtos", ""));
//        String name = cashierMsgDtos.get(which).getName();
        tvCashier.setText("");
        lvGoods.setAdapter(adapter);
        setSwipeListView();
        setData();
    }

    public void setData() {
        double dou = 0;
        for (int i = 0; i < goodsDtos.size(); i++) {
            dou = dou + goodsDtos.get(i).getNum() * goodsDtos.get(i).getPrice() - goodsDtos.get(i).getDiscount();
        }
        BigDecimal b = new BigDecimal(Double.parseDouble(String.valueOf(dou)));
        double f1 = b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        tvMoney.setText(String.valueOf(f1));
    }

    private void setSwipeListView() {
        // step 1. create a MenuCreator
        SwipeMenuCreator creator = new SwipeMenuCreator() {
            @Override
            public void create(SwipeMenu menu) {
                // create "open" item
                SwipeMenuItem openItem = new SwipeMenuItem(
                        getApplicationContext());
                // set item background
                openItem.setBackground(new ColorDrawable(Color.rgb(0xD9, 0x47,
                        0x47)));
                // set item width
                openItem.setWidth(dp2px(90));
                // set item title
                openItem.setTitle("删除");
                // set item title fontsize
                openItem.setTitleSize(18);
                // set item title font color
                openItem.setTitleColor(Color.WHITE);
                // add to menu
                menu.addMenuItem(openItem);
            }
        };
        // set creator
        lvGoods.setMenuCreator(creator);

        // step 2. listener item click event
        lvGoods.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public void onMenuItemClick(int position, SwipeMenu menu, int index) {
                GoodsDto item = goodsDtos.get(position);
//					delete(item);
                goodsDtos.remove(position);
                adapter.notifyDataSetChanged();
                setData();
            }
        });

        // set SwipeListener
        lvGoods.setOnSwipeListener(new SwipeMenuListView.OnSwipeListener() {

            @Override
            public void onSwipeStart(int position) {
                // swipe start
            }

            @Override
            public void onSwipeEnd(int position) {
                // swipe end
            }
        });
    }

    private int dp2px(int dp) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
                getResources().getDisplayMetrics());
    }
    Intent intent;
    @OnClick({R.id.retain, R.id.settle, R.id.iv_vip, R.id.iv_scan,R.id.vip_serach,R.id.tv_qd})
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.tv_qd:
                startActivity(RestOrderActivity.class);
                break;
            case R.id.vip_serach:
                vipDialog();

                break;
            case R.id.iv_vip:
                startActivity(PointSelectActivity.class);
                break;
            case R.id.iv_scan:
                requestCemera();
                break;
            case R.id.retain:
                if (retain.getText().equals("挂单")) {
                    if (goodsDtos.isEmpty()) {
                        showToast("请添加商品");
                    } else {
                        final AlertDialog deleteDialog = new AlertDialog.Builder(this)
                                .setTitle("提示")
                                .setMessage("确定挂单？")
                                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        addRestOrderinfo();
                                    }
                                }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {

                                    }
                                })
                                .create();
                        deleteDialog.show();
                    }

                } else {
                    startActivity(RestOrderActivity.class);
                }

                break;
            case R.id.settle:
                UnionConfig.accessToken();
                if (goodsDtos.isEmpty()) {
                    showToast("请添加商品");
                } else {
                    String prodicountAll = util.checkbill(Double.parseDouble(tvMoney.getText().toString()));
                    String prodiscount = util.chekDetail(goodsDtos);
                    String dismoney = "0";
                    if (prodicountAll.contains("%")) {
                        double ss = Double.parseDouble(tvMoney.getText().toString());
                        double re = ss * (1 - Double.parseDouble(prodicountAll.substring(0, prodicountAll.length() - 1))/100);
                        if (re > Double.parseDouble(prodiscount)) {
                            dismoney = prodicountAll;
                        } else {
                            dismoney = prodiscount;
                        }
                    }  else {
                        dismoney = Double.parseDouble(prodicountAll) > Double.parseDouble(prodiscount) ? prodicountAll : prodiscount;
                    }


                    SaveOrderInfo.saveAsJson(getApplicationContext(), goodsDtos);
                    intent = new Intent(ScanReceiptActivity.this, PayActivity.class);
                    intent.putExtra(PUT_MONEY, Double.parseDouble(tvMoney.getText().toString()));
                    intent.putExtra(PUT_MAXNO, maxNO);
                    intent.putExtra("tableBeen", new Tablebeen());
                    intent.putExtra("pro", dismoney);
                    intent.putExtra("vip", vipBeen);
                    startActivity(intent);
//                    goodsDtos.clear();
//                    adapter.notifyDataSetChanged();
//                    setData();
                }
                break;
            case R.id.order_detail:
//                LayoutInflater mLayoutInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
//                View contentView = mLayoutInflater.inflate(R.layout.scan_recepit_detail, null);
//                // R.layout.pop为PopupWindow 的布局文件
//                PopupWindow pop = new PopupWindow(contentView, ActionBar.LayoutParams.FILL_PARENT, TurnSize.dip2px(getApplicationContext(), 150));
//                pop.setBackgroundDrawable(new BitmapDrawable());
//                // 指定 PopupWindow 的背景
//                pop.setFocusable(true);
//                //指定PopupWindow显示在你指定的view下
//
//                int[] location = new int[2];
//                llBottom.getLocationOnScreen(location);
//                pop.showAtLocation(llBottom, Gravity.NO_GRAVITY, location[0], location[1] - pop.getHeight());
//
//                TextView ys = (TextView) contentView.findViewById(R.id.detail_ys);
//                TextView dMoney = (TextView) contentView.findViewById(R.id.detail_discount_money);
//                TextView dNum = (TextView) contentView.findViewById(R.id.detail_discount_num);
//                TextView nMoney = (TextView) contentView.findViewById(R.id.detail_normal_money);
//                TextView nNum = (TextView) contentView.findViewById(R.id.detail_normal_num);
//                TextView num = (TextView) contentView.findViewById(R.id.detail_num);
//
//                double Nmoney = 0;
//                int Nnum = 0;
//
//                double discountMoney = 0;
//                int discountNum = 0;
//                int totalNum = 0;
//                for (int i = 0; i < goodsDtos.size(); i++) {
//                    totalNum += goodsDtos.get(i).getNum();
//                    if (goodsDtos.get(i).getDiscount() > 0) {
//                        discountNum += goodsDtos.get(i).getNum();
//                        discountMoney += goodsDtos.get(i).getDiscount();
//                    } else {
//                        Nnum += goodsDtos.get(i).getNum();
//                        Nmoney += goodsDtos.get(i).getNum() * goodsDtos.get(i).getPrice();
//                    }
//                }
//
//                ys.setText(tvMoney.getText().toString());
//                nMoney.setText(String.valueOf(Nmoney));
//                nNum.setText(String.valueOf(Nnum));
//                dMoney.setText(String.valueOf(discountMoney));
//                dNum.setText(String.valueOf(discountNum));
//                num.setText(String.valueOf(totalNum));
                break;
        }
    }

    MClearEditText sl;
    private void vipDialog() {
        new CircleDialog.Builder(this)
                .setBodyView(R.layout.vip_dialog, new OnCreateBodyViewListener() {
                    @Override
                    public void onCreateBodyView(View view) {
                        sl = view.findViewById(R.id.et_goods_num);
//                        dj = view.findViewById(R.id.et_goods_dj);
                        sl.addTextChangedListener(new TextWatcher() {
                            @Override
                            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                            }

                            @Override
                            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                            }

                            @Override
                            public void afterTextChanged(Editable editable) {
                                isHide = true;
                            }
                        });

                    }
                })
                .setPositive("查询", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        hintKbOne();
                        search();
                    }
                })
                .setCancelable(false)
                .setTitle("提示")
                .setNegative("取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        hintKbOne();
                    }
                })
                .show();
    }

    VipBeen vipBeen;
    private void search() {
        showDialog();
        RequestParams params = new RequestParams();
        params.put("logid", SPHelper.getInstance().getString(Constant.USER_ID));
        params.put("sysid", SPHelper.getInstance().getString(Constant.SYS_ID));
        params.put("model", "base.mselect");
        params.put("fun", "getvipinfo");

        JSONObject object = new JSONObject();
        try {
            object.put("num", sl.getText().toString().trim());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        params.put("pds", object.toString());
        LoadServer.getConnect(this, Api.LOGIN, params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                Log.i("vip", new String(bytes));
                try {
                    JSONObject object = new JSONObject(new String(bytes));
                    String code = object.getString("errCode");
                    final String msg = object.getString("errMsg");
                    if (code.equals("100")) {
                        vipBeen = new Gson().fromJson(object.getJSONObject("result").toString(), VipBeen.class);
                        Message message = Message.obtain();
                        message.what = 1;
                        handler.sendMessage(message);
                    } else {
                        Message message = Message.obtain();
                        message.what = 3;
                        handler.sendMessage(message);
                    }


                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {

            }
        });
    }
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    close();
                    tvOrderId.setText("会员号："+vipBeen.getNum());
                    Toast.makeText(ScanReceiptActivity.this, "查询成功", Toast.LENGTH_SHORT).show();
                    break;
                case 3:
                    close();
                    Toast.makeText(ScanReceiptActivity.this, "未查询到数据", Toast.LENGTH_SHORT).show();
                    break;
            }

        }
    };


    private boolean isHide = false;
    private void hintKbOne() {
        if (isHide) {
            InputMethodManager imm = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
            // 得到InputMethodManager的实例
            if (imm.isActive()) {
                // 如果开启
                imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT,
                        InputMethodManager.HIDE_NOT_ALWAYS);

            }
            isHide = false;
        }

    }


    /**
     * 获取扫码返回的信息
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 2) {
            if (requestCode == 1) {
//                saleEt.setText(data.getStringExtra("code"));
                judgeCode(data.getStringExtra("code"));
            }
        }
    }
    private void requestCemera() {
        if (PermissionsUtil.hasPermission(this, Manifest.permission.CAMERA)) {
            //有访问摄像头的权限
            intent = new Intent(ScanReceiptActivity.this, CaptureActivity.class);
            startActivityForResult(intent, 1);
        } else {
            PermissionsUtil.requestPermission(this, new PermissionListener() {
                @Override
                public void permissionGranted(@NonNull String[] permissions) {
                    //用户授予了访问摄像头的权限
                    intent = new Intent(ScanReceiptActivity.this, CaptureActivity.class);
                    startActivityForResult(intent, 1);
                }


                @Override
                public void permissionDenied(@NonNull String[] permissions) {
                    //用户拒绝了访问摄像头的申请
                }
            }, new String[]{Manifest.permission.CAMERA});
        }
    }

    /**
     * 判断数据库里面是否有该条形码的商品
     *
     * @param code 商品的条形码
     */
    public void judgeCode(String code) {
        Log.i("code", code);
        GoodsDto goodsDto = goodsDao.selectGoods(code);
        util.getUsePro();
        if (goodsDto != null) {//当返回的查询数据不为空的时候

            util.checkSinglePro(goodsDto);
            List<GoodsDto> zpList = util.checkGivePro(goodsDto);//获取赠品
            check(goodsDto);
            if (zpList.size() != 0) {
                if (zpList.get(0).getLogic().equals("2")) {//选一个商品
                    showSelect(zpList);
                } else {
                    goodsDtos.addAll(zpList);
                }
            } else {
                List<GoodsDto> zpslist = util.check(goodsDtos);
                goodsDtos.addAll(zpslist);
            }

        } else {
            Toast.makeText(this, "商品不存在", Toast.LENGTH_SHORT).show();
        }

        setData();
        adapter.notifyDataSetChanged();
        saleEt.setText("");
    }

    //单选赠品
    private DialogFragment dialogFragment;
    private void showSelect(final List<GoodsDto> zpList) {
       dialogFragment =  new CircleDialog.Builder(this)
                .setBodyView(R.layout.select_zp, new OnCreateBodyViewListener() {
                    @Override
                    public void onCreateBodyView(View view) {
                        ListView listView = view.findViewById(R.id.zp_list);
                        listView.setAdapter(new ZpAdapter(zpList));
                        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                                goodsDtos.add(zpList.get(i));
                                adapter.notifyDataSetChanged();
                                dialogFragment.dismiss();
                            }
                        });
                    }
                })
                .setCancelable(false)
                .setTitle("请选择一个赠品")
                .setNegative("取消",null)
                .show();
    }

    class ZpAdapter extends BaseAdapter {
        private List<GoodsDto> zpList;

        public ZpAdapter(List<GoodsDto> zpList) {
            this.zpList = zpList;
        }

        @Override
        public int getCount() {
            return zpList.size();
        }

        @Override
        public Object getItem(int i) {
            return zpList.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            Zpholder zpholder;
            if (view == null) {
                zpholder = new Zpholder();
                view = LayoutInflater.from(ScanReceiptActivity.this).inflate(R.layout.zp_list_item, null);
                zpholder.name = view.findViewById(R.id.tv_name);
                view.setTag(zpholder);

            } else {
                zpholder = (Zpholder) view.getTag();
            }
            zpholder.name.setText(zpList.get(i).getName());

            return view;
        }
        class Zpholder{
            TextView name;
        }
    }


    private void check(GoodsDto gd){
        for (GoodsDto dto : goodsDtos) {
            if (dto.getSid().equals(gd.getSid())) {
                dto.setNum(DoubleSave.doubleSaveTwo(dto.getNum() + 1));

                if (dto.getProType().equals(Constant.PRO_N_REDUCE)) {
                    if (dto.getNum() == dto.getMuchnum()) {
                        dto.setCxzk(DoubleSave.doubleSaveTwo(dto.getPrice() - dto.getProPrice()));
                    }
                } else {
                    if (dto.getNum() <= dto.getSingnum() &&dto.getNum()>=dto.getMuchnum()) {
                        dto.setCxzk(DoubleSave.doubleSaveTwo(dto.getNum() * dto.getPrice() - dto.getNum() * dto.getProPrice() + dto.getPrice() * (1 - dto.getProDiscout()) * dto.getNum()));
                    }
                }

                return;
            }
        }
        goodsDtos.add(gd);
    }


    /**
     * 删除当前的订单的信息
     */
    public void deleteOrder() {
        if (goodsDtos.isEmpty()) {
            showToast("商品为空");
        } else {
            final AlertDialog deleteDialog = new AlertDialog.Builder(this)
                    .setTitle("提示")
                    .setMessage("确定销毁该订单？")
                    .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            goodsDtos.clear();
                            adapter.notifyDataSetChanged();
                            tvMoney.setText("0.0");
                        }
                    }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    })
                    .create();
            deleteDialog.show();
        }

    }

    public void addRestOrderinfo() {
        if (vipBeen != null) {
            vipinfo = new Gson().toJson(vipBeen, VipBeen.class);
        }
        String shopId = SPHelper.getInstance().getString(Constant.STORE_ID);
        OrderDto orderDto = new OrderDto();
        orderDto.setOrder_info(SaveOrderInfo.changeGoodDtoToJson(goodsDtos));//存储的该订单的商品的信息
        orderDto.setPayway(null);
        orderDto.setTime(GetData.getYYMMDDTime());
        orderDto.setSs_money(0.00);
        orderDto.setYs_money(DoubleSave.doubleSaveTwo(Double.parseDouble(tvMoney.getText().toString())));
        orderDto.setZl_money(0.00);
        orderDto.setCashiername("");
        orderDto.setCashiernumber("");
        orderDto.setShop_id(shopId);
        orderDto.setOrderType(Constant.ORDERTYPE_GD);
        orderDto.setMaxNo(maxNO);
        orderDto.setmTableId(vipinfo);
        orderDto.setmTableNumber("");
        orderDto.setCheckoutTime(GetData.getDataTime());
        orderDto.setDetailTime(GetData.getHHmmssTimet());
        orderDto.setHasReturnGoods(Constant.hasReturnGoods_No);
        orderDto.setOut_trade_no(null);
        //当挂单的时候该数据用于保存是哪个界面进行的挂单操作
        orderDto.setPayReturn(RestOrderActivity.REST_SCAN);
        orderDto.setIfFinishOrder(Constant.NO);
        /**
         * 给数据库里面添加一条记录
         */
        new OrderDao(getApplicationContext()).addOrder(orderDto);
        vipBeen = null;
        tvOrderId.setText("会员号：");
        goodsDtos.clear();
        adapter.notifyDataSetChanged();
        tvMoney.setText("0");
        showToast("挂单成功");
    }

    class DialogClickListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.btn_detail_cancle:
                    diacountDialog.dismiss();
                    break;
                case R.id.btn_detail_sure:
                    if (0 == Double.parseDouble(et_num.getText().toString())) {
                        goodsDtos.remove(selectGood);
                        adapter.notifyDataSetChanged();
                        diacountDialog.dismiss();
                    } else {
                        selectGood.setNum(Double.parseDouble(et_num.getText().toString()));
                        if (radioButton_zc.isChecked()) {
                            discount(radioButton_zc, et_zc);
                        } else if (radioButton_zr.isChecked()) {
                            discount(radioButton_zr, et_zr);
                        }
                        adapter.notifyDataSetChanged();
                        setData();
                        diacountDialog.dismiss();

                    }
                    break;
                case R.id.iv_jia:
                    try {
                        double num = Double.parseDouble(et_num.getText().toString());
                        num += 1;
                        et_num.setText(String.valueOf(num));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case R.id.iv_jian:
                    try {
                        double num = Double.parseDouble(et_num.getText().toString());
                        if (num == 0) {
                            showToast("商品数量不可小于0!");
                        } else {
                            num -= 1;
                            et_num.setText(String.valueOf(num));
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
            }
        }
    }

    public void discount(RadioButton button, EditText et) {
        if (!et.getText().toString().trim().isEmpty()) {
            double value = Double.parseDouble(et.getText().toString().trim());
            if (value > 0) {
                if (button.getId() == R.id.radioButton_zc) {
                    if (value > 100) {
                        showToast("折让金额不能大于商品金额");
                    } else {
                        double discount = selectGood.getPrice() * selectGood.getNum() * (value / 100);
                        selectGood.setLszk(DoubleSave.doubleSaveTwo(discount));
                    }
                } else if (button.getId() == R.id.radioButton_zr) {
                    if (value > selectGood.getPrice() * selectGood.getNum()) {
                        showToast("折让金额不能大于商品金额");
                    } else {
                        selectGood.setLszk(value);
                    }
                }
            }

        }

    }

    class DialogRadioButton implements CompoundButton.OnCheckedChangeListener {

        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            switch (buttonView.getId()) {
                case R.id.radioButton_zc:
                    if (isChecked) {
                        radioButton_zc.setChecked(true);
                        radioButton_zr.setChecked(false);
                        et_zr.setText(null);
                    }
                    break;
                case R.id.radioButton_zr:
                    if (isChecked) {
                        radioButton_zc.setChecked(false);
                        radioButton_zr.setChecked(true);
                        et_zc.setText(null);
                    }
                    break;
            }
        }
    }
    private void showitem(){
        TopRightMenu topRightMenu = new TopRightMenu(this);
        //添加菜单项
        List<MenuItem> menuItems = new ArrayList<>();

        menuItems.add(new MenuItem(R.drawable.icon_qd, "取单"));
        menuItems.add(new MenuItem(R.drawable.icon_zk, "整单折扣"));
        menuItems.add(new MenuItem(R.drawable.icon_qk, "清空"));
        topRightMenu.setHeight(480)
                .setWidth(320)
                .showIcon(true)
                .addMenuList(menuItems)
                .showAsDropDown(getMenu(), -225, 10);

    }
}

